package com.itms.tool;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.itms.tool.data.DatabaseHelper;
import com.j256.ormlite.android.apptools.OpenHelperManager;

public abstract class BaseActivity extends SherlockFragmentActivity {

	public static final String ARGS = "args";

	private DatabaseHelper mHelper;
	private boolean mDestroyed;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
	}
	
	public DatabaseHelper getHelper() {
		if (mHelper == null) {
			throw new IllegalStateException(getClass() + ".onCreate has not been called yet");
		} else if (mDestroyed) {
			throw new IllegalStateException(getClass() + " has been destroyed");
		}
		return mHelper;
	}
	
	public void startActivity(Class<?> cls) {
		startActivity(cls, null);
	}

	public void startActivity(Class<?> cls, Bundle args) {
		Intent i = new Intent(this, cls);
		setArgs(i, args);
		startActivity(i);
	}

	public void setArgs(Intent intent, Bundle args) {
		if (args != null) {
			intent.putExtra(ARGS, args);
		}
	}

	public Bundle getArgs() {
		return getIntent().getBundleExtra(ARGS);
	}

	public void toast(int message) {
		toast(message, Toast.LENGTH_SHORT);
	}

	public void toast(int message, int length) {
		Toast.makeText(this, message, length).show();
	}

	public void toast(String message) {
		toast(message, Toast.LENGTH_SHORT);
	}

	public void toast(String message, int length) {
		Toast.makeText(this, message, length).show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		OpenHelperManager.releaseHelper();
		mDestroyed = true;
	}
}
